<template>
  <div id="register">
    <el-form
        :model="userInfo"
        status-icon
        :rules="rules"
        label-width="60px"
        class="register-form"
    >
      <!--   标题   -->
      <h3 class="title">注册</h3>
      <!--  用户名  -->
      <el-form-item label="邮箱" prop="name" class="form-input">
        <el-input
            v-model="userInfo.name"
            type="text"
            autocomplete="off"
            placeholder="邮箱"
            size="medium"
        ></el-input>
      </el-form-item>
      <!--  密码  -->
      <el-form-item label="密码" prop="pass" class="form-input">
        <el-input
            v-model="userInfo.pass"
            type="password"
            autocomplete="off"
            placeholder="密码"
            size="medium"
        ></el-input>
      </el-form-item>
      <!--  验证码  -->
      <el-form-item label="验证码" prop="code" class="form-input verify-code">
        <el-input
            v-model="userInfo.code"
            type="text"
            autocomplete="off"
            placeholder="验证码"
            size="medium"
        ></el-input>
        <el-button class="send-btn" type="primary" @click.prevent="sendCode"
                   size="medium">
          发送验证码
        </el-button>
      </el-form-item>
      <!--  提交按钮  -->
      <el-form-item class="form-input">
        <el-button class="submit-btn" type="primary" @click="register"
                   size="medium">
          注册
        </el-button>
      </el-form-item>
      <a href="/login" class="to-register">已有账号？去登陆</a>
    </el-form>
  </div>

</template>

<script lang="ts">
import {ElMessage} from 'element-plus'
import {reactive, watch} from 'vue'
import $, { param } from "jquery"
import {POST} from "@/api";
import {useRouter} from 'vue-router'

export default {
  name: "Register",
  setup() {
    const router = useRouter();

    const userInfo = reactive({
      name: '',
      pass: '',
      code: ''
    })
    const isLogin = reactive({
      nameNotNull: false,
      passNotNull: false,
      codeNotNull: false
    })
    // 验证用户名
    const validateName = (rule: object, value: any, callback: any) => {
      // 邮箱验证码正则表达式
      const emailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
      if (value === '') {
        callback(new Error('请输入邮箱'))
      } else if (!emailReg.test(value)) {
        callback(new Error("邮箱格式不正确，请输入类似：example@qq.com"))
      } else {
        isLogin.nameNotNull = true
        callback()
      }
    }
    // 验证密码
    const validatePass = (rule: object, value: any, callback: any) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        isLogin.passNotNull = true
        callback()
      }
    }
    // 验证邮箱
    const validateEmail = (rule: object, value: any, callback: any) => {
      if (value === '') {
        callback(new Error('请输入验证码'))
      } else {
        isLogin.passNotNull = true
        callback()
      }
    }

    // 设置提交按钮是否可用于提交数据
    watch(userInfo, (v1, v2) => {
      // 邮箱验证码正则表达式
      const emailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;

      isLogin.nameNotNull = userInfo.name !== "" && userInfo.name != null && emailReg.test(userInfo.name)
      isLogin.passNotNull = userInfo.pass !== "" && userInfo.pass != null
      isLogin.codeNotNull = userInfo.code !== "" && userInfo.code != null

      if (isLogin.nameNotNull && isLogin.passNotNull) {
        $(".verify-code").show().css("display", "flex")
      }
    })
    // 设置定时器标识
    let timer: number = 0
    const sendCode = () => {
      // 为按钮设置淡蓝色
      $(".send-btn").attr("type", "info")
      // 设置点击下一次发送所需要的时间
      let time = 60
      // 首先清除上次的定时器
      clearInterval(timer)
      // 设置定时器
      timer = setInterval(() => {
        if (time <= 1) {
          clearInterval(timer)
        }
        $(".send-btn").text("请耐心等待 " + (--time) + " 秒")
        if (time == 0) {
          // 设置按钮为原来的样式
          $(".send-btn").text("发送验证码")
          $(".send-btn").attr("type", "primary")
        }
      }, 1000)

      // TODO 调用接口给用户邮箱发送验证码
      // BUG 点击发送按钮还是可以发送
      console.log("发送验证码")
    }

    const register = () => {
      if (isLogin.nameNotNull && isLogin.passNotNull && isLogin.codeNotNull) {
        // TODO 注册代码
        POST("/user/register", {
          "username": userInfo.name,
          "password": userInfo.pass
        }).then(res => {
          console.log(res)
          if (res.status === 200) {
            ElMessage.success("注册成功，即将跳转到登录页面")
            setTimeout(() => {
              router.push("/login")
            }, 2000)
          } else {
            ElMessage.warning(res.data)
          }
        }).catch(err => {
           console.log(err)
          ElMessage.error(err.data)
        })
      } else if (!isLogin.codeNotNull && !isLogin.nameNotNull) {
        ElMessage.error("邮箱格式不正确")
      } else if (!isLogin.codeNotNull && isLogin.nameNotNull) {
        ElMessage.error("请输入验证码")
      } else {
        ElMessage.error("用户名和密码不能为空")
      }
    }

    const rules = {
      name: [{validator: validateName, trigger: 'blur'}],
      pass: [{validator: validatePass, trigger: 'blur'}],
      code: [{validator: validateEmail, trigger: 'blur'}]
    }
    return {
      register,
      userInfo,
      rules,
      isLogin,
      sendCode
    }
  },
}
</script>

<style lang="scss" scoped>
#register {
  position: fixed;
  background-image: url("../static/login-bgc.jpg");
  background-clip: padding-box;
  width: 100%;
  height: 100%;
  background-size: cover;
  text-align: center;

  .register-form {
    width: 450px;
    box-shadow: 1px 1px 10px 10px #eee;
    padding: 20px 30px 20px 10px;
    border-radius: 20px;
    margin: 120px auto 0;

    .form-input {
      margin-top: 30px;
    }

    .verify-code {
      width: 60%;
      display: none;
    }

    .send-btn {
      position: absolute;
      margin-left: 30px;
      margin-top: 2px;
    }

    .submit-btn {
      width: 100%;
    }

    .to-register {
      display: block;
      text-align: right;
      font-size: 13px;
    }
  }
}
</style>